package com.sgcc.sx.pmos.mobileapp.activity;

import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.widget.NestedScrollView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.sgcc.sx.pmos.arouter.app.AppArouterPath;
import com.sgcc.sx.pmos.arouter.personalcenter.PersonalCenterArouterPath;
import com.sgcc.sx.pmos.common.base.MvpBaseActivity;
import com.sgcc.sx.pmos.common.utils.ImmersionBarUtils;
import com.sgcc.sx.pmos.common.utils.SoftKeyBoardListener;
import com.sgcc.sx.pmos.common.utils.UserManager;
import com.sgcc.sx.pmos.common.utils.VisibilConfig;
import com.sgcc.pmos.nativesdk.R;
import com.sgcc.ln.pmos.common.widget.keybord.KeyboardUtil;
import com.sgcc.ln.pmos.common.widget.keybord.MyKeyboardView;
import com.sgcc.sx.pmos.mobileapp.bean.ConfigBean;
import com.sgcc.sx.pmos.mobileapp.contract.LoginContract;
import com.sgcc.sx.pmos.mobileapp.presenter.LoginPresenter;


/**
 * 登录界面
 */
@Route(path = AppArouterPath.APP_LOGIN)
public class LoginActivity extends MvpBaseActivity<LoginPresenter> implements LoginContract.View {

    private EditText mEtName;
    private EditText mEtPassword;
    private CheckBox mCbCheckPwd;
    private CheckBox mCheckbox;
    private RelativeLayout mRlLogin;
    private RelativeLayout mRlBack;
    private NestedScrollView mNsvContent;
    private LinearLayout mLlContent;
    private View mVStatusBar;
    private TextView tv_user_agreement, tv_privacy;
    private TextView mTvRegistered;


    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_login;
    }

    @Override
    protected LoginPresenter createPresenter() {
        return new LoginPresenter();
    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (TextUtils.isEmpty(mEtPassword.getText().toString().trim())) {
                mCbCheckPwd.setVisibility(View.GONE);
            } else {
                mCbCheckPwd.setVisibility(View.VISIBLE);
            }
            if (!TextUtils.isEmpty(mEtName.getText().toString().trim()) && !TextUtils.isEmpty(mEtPassword.getText().toString().trim())) {
                mRlLogin.setBackground(mContext.getResources().getDrawable(R.drawable.bg_login_btn_3274f0));
                mRlLogin.setClickable(true);
                mRlLogin.setEnabled(true);
            } else {
                mRlLogin.setBackground(mContext.getResources().getDrawable(R.drawable.bg_login_btn_993274f0));
                mRlLogin.setClickable(false);
                mRlLogin.setEnabled(false);
            }
        }
    };

    @Override
    protected void initViews() {
        super.initViews();
        ImmersionBarUtils.initTranslBar(LoginActivity.this);
        findViewByIds();

        KeyboardUtil keyboardUtil = new KeyboardUtil(this, mNsvContent);
        keyboardUtil.setRandom(false)
                .setKeybordTYpe(MyKeyboardView.KEYBOARDTYPE_ABC)
                .bindKeyboard(mEtName, mEtPassword);//自定义键盘
    }

    private void findViewByIds() {
        mEtName = (EditText) findViewById(R.id.et_name);
        mEtPassword = (EditText) findViewById(R.id.et_password);
        mCbCheckPwd = (CheckBox) findViewById(R.id.cb_check_pwd);
        mCheckbox = (CheckBox) findViewById(R.id.checkbox);
        mRlLogin = (RelativeLayout) findViewById(R.id.rl_login);
        mRlBack = (RelativeLayout) findViewById(R.id.rl_back);
        mNsvContent = (NestedScrollView) findViewById(R.id.nsv_content);

        mLlContent = (LinearLayout) findViewById(R.id.ll_content);
        mTvRegistered = (TextView) findViewById(R.id.tv_registered);

        mVStatusBar = (View) findViewById(R.id.view_status_bar);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, BarUtils.getStatusBarHeight());
        mVStatusBar.setLayoutParams(params);

        tv_user_agreement = (TextView) findViewById(R.id.tv_user_agreement);
        tv_privacy = (TextView) findViewById(R.id.tv_privacy);
        tv_user_agreement.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //用户协议
                ARouter.getInstance()
                        .build(PersonalCenterArouterPath.PERSONALCENTER_USERAGREEMENT)
                        .navigation();
            }
        });
        tv_privacy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //隐私政策
                ARouter.getInstance()
                        .build(PersonalCenterArouterPath.PERSONALCENTER_PRIVACYPOLICY)
                        .navigation();
            }
        });

        mEtName.addTextChangedListener(textWatcher);
        mEtPassword.addTextChangedListener(textWatcher);

        mCbCheckPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!isChecked) {
                    //选择状态 显示明文--设置为可见的密码
                    mEtPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    //默认状态显示密码--设置文本 要一起写才能起作用 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
                    mEtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
            }
        });


        if (!TextUtils.isEmpty(mEtName.getText().toString().trim()) && !TextUtils.isEmpty(mEtPassword.getText().toString().trim())) {
            mRlLogin.setBackground(mContext.getResources().getDrawable(R.drawable.bg_login_btn_3274f0));
            mRlLogin.setClickable(true);
            mRlLogin.setEnabled(true);
        } else {
            mRlLogin.setBackground(mContext.getResources().getDrawable(R.drawable.bg_login_btn_993274f0));
            mRlLogin.setClickable(false);
            mRlLogin.setEnabled(false);
        }

        mRlLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPresenter.getVisibilConfig();
//                if (mCheckbox.isChecked()) {
//                    String username = mEtName.getText().toString().trim();
//                    String password = mEtPassword.getText().toString().trim();
//                    if (VisibilConfig.isUserCanLog()) {
//                        mPresenter.startLogin(username, password);
//                    } else {
//                        ToastUtils.showShort("该用户暂时无法登录。");
//                    }
//
//                } else {
//                    ToastUtils.showShort("请先阅读并同意用户协议和隐私政策");
//                }

            }
        });

        SoftKeyBoardListener.setListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                mLlContent.setVisibility(View.GONE);
            }

            @Override
            public void keyBoardHide(int height) {
                mLlContent.setVisibility(View.VISIBLE);
            }
        });
        mRlBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        mTvRegistered.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //去注册
                ARouter.getInstance()
                        .build(AppArouterPath.APP_REGISTERED)
                        .navigation();
            }
        });
    }


    @Override
    public void LoginSuccess() {
        finish();
    }

    @Override
    public void LoginFailed() {

    }

    @Override
    public void goRegistered(String data) {
        //data -1实名认证，空字符串为工商信息，1法定代表人，2联系信息，3联系人信息，4户号信息，
        // 5银行信息，6审核中，8审核驳回
        if (data.equals("6")) {
            ARouter.getInstance()
                    .build(AppArouterPath.APP_AUDITSTATEACTIVITY)
                    .withInt("position", Integer.parseInt(data))
                    .navigation();
        } else {
            new XPopup.Builder(ActivityUtils.getTopActivity())
                    .dismissOnBackPressed(false)
                    .dismissOnTouchOutside(false)
                    .asConfirm("温馨提示", "账号企业信息不完整，请完善企业信息后再登录！",
                            "退出", "立即完善",
                            new OnConfirmListener() {
                                @Override
                                public void onConfirm() {
                                    ARouter.getInstance()
                                            .build(AppArouterPath.APP_ASSOCIATEDENTERPRISEINFO)
                                            .withString("position", data)
                                            .navigation();
                                }
                            }, new OnCancelListener() {
                                @Override
                                public void onCancel() {
                                    UserManager.logout();
                                }
                            }, false).show();
        }
    }

    @Override
    public void goRegistered(String data, String text) {
        if (data.equals("8")) {
            ARouter.getInstance()
                    .build(AppArouterPath.APP_AUDITSTATEACTIVITY)
                    .withInt("position", Integer.parseInt(data))
                    .withString("text", text)
                    .navigation();
        }

    }

    @Override
    public void queryVisibilConfigFailed() {
        ToastUtils.showShort("服务异常，请重试");

    }

    @Override
    public void queryVisibilConfigSuccess(ConfigBean response) {
        if (response != null) {
            if (response.getCode() == 200) {
                if (response.getData() != null && response.getData().size() != 0) {
                    for (int i = 0; i < response.getData().size(); i++) {
                        if (TextUtils.equals("isAllowLogin", response.getData().get(i).getParamId())) {
                            if (TextUtils.equals("0", response.getData().get(i).getParamValue())) {
                                VisibilConfig.setUserCanLog(false);
                            } else if (TextUtils.equals("1", response.getData().get(i).getParamValue())) {
                                VisibilConfig.setUserCanLog(true);
                            }
                        }
                    }
                }
                if (mCheckbox.isChecked()) {
                    String username = mEtName.getText().toString().trim();
                    String password = mEtPassword.getText().toString().trim();
                    if (VisibilConfig.isUserCanLog()) {
                        mPresenter.startLogin(username, password);
                    } else {
                        ToastUtils.showShort("当前时间暂不能登录");
                    }

                } else {
                    ToastUtils.showShort("请先阅读并同意用户协议和隐私政策");
                }
            } else {
                ToastUtils.showShort("服务异常，请重试");
            }

        } else {
            ToastUtils.showShort("服务异常，请重试");
        }
    }
}
